#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>

#define SERVER_IP   "127.0.0.1"
#define SERVER_PORT 8080

#define BUFF_SIZE 	1024

int main()
{
	int ret = 0;
	char buf[BUFF_SIZE] = {0};
	
	struct sockaddr_in sockaddr_svr = {0};
	int sock_svr = 0;
	
	/* create a socket */
	sock_svr = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
	if( -1 == sock_svr )
	{
		printf( "create sock error\n" );
		return -1;
	}
	
	/* sockaddr info the server */
	sockaddr_svr.sin_family = AF_INET;
	sockaddr_svr.sin_port = htons( SERVER_PORT );
	sockaddr_svr.sin_addr.s_addr = htonl(INADDR_ANY);
	
	/* bind sockaddr_svr & sock_svr */
	ret = bind( sock_svr, (struct sockaddr *)&sockaddr_svr, sizeof(sockaddr_svr) );
	if( -1 == ret )
	{
			printf( "bind failed!\n" );
			return -1;
	}
	
	printf( "bind success. SVR_PORT: %d\n", SERVER_PORT );
	
	/* echo data here */
	while( 1 )
	{
		memset( buf, 0, BUFF_SIZE );
		
		struct sockaddr_in sockaddr_cln = {0};
		socklen_t sockaddr_len = sizeof(sockaddr_cln);
		
		ret = recvfrom( sock_svr, buf, BUFF_SIZE, 0, (struct sockaddr*)&sockaddr_cln, &sockaddr_len );
		printf( "ret:%d, %s\n", ret, buf );
	}
	
	/* clean up */
	close( sock_svr );
	
	sleep( 5 );
	return 0;
}